package cn.schoolwow.quickflow.service.executor;

import cn.schoolwow.quickflow.domain.FlowExecutorConfig;
import cn.schoolwow.quickflow.service.executor.business.QuickFlowExecutorBusinessOperationImpl;
import cn.schoolwow.quickflow.service.executor.option.QuickFlowExecutorOptionOperationImpl;
import cn.schoolwow.quickflow.service.executor.putData.QuickFlowExecutorPutDataOperationImpl;
import cn.schoolwow.quickflow.service.executor.putInstanceData.QuickFlowExecutorPutInstanceDataOperationImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 执行器代理模式对象
 */
public class QuickFlowExecutorInvocationHandler implements InvocationHandler {
    private Object[] interfaceInstanceArray;

    public QuickFlowExecutorInvocationHandler(FlowExecutorConfig flowExecutorConfig) {
        interfaceInstanceArray = new Object[]{
                new QuickFlowExecutorBusinessOperationImpl(flowExecutorConfig),
                new QuickFlowExecutorPutDataOperationImpl(flowExecutorConfig),
                new QuickFlowExecutorPutInstanceDataOperationImpl(flowExecutorConfig),
                new QuickFlowExecutorOptionOperationImpl(flowExecutorConfig)
        };
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String interfaceName = method.getDeclaringClass().getSimpleName();
        for(Object interfaceInstance:interfaceInstanceArray){
            Class interfaceClass = interfaceInstance.getClass().getInterfaces()[0];
            if(interfaceClass.getSimpleName().equalsIgnoreCase(interfaceName)){
                try {
                    return method.invoke(interfaceInstance, args);
                }catch (InvocationTargetException e){
                    Throwable targetException = e.getTargetException();
                    throw targetException;
                }
            }
        }
        throw new IllegalAccessError("不支持调用该方法!方法名:"+method.getName());
    }
}
